import React, { Component } from 'react';
import { Table, Switch, Button, Input, message, Progress, Slider, Carousel, Form, Upload, Drawer, DatePicker, Select } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import Pro from '../../api/pro';
class Index extends Component {
    state = {
        proList: [],
        page: 1,
        contentStyle: {
            margin: 0,
            height: '160px',
            color: '#fff',
            lineHeight: '160px',
            textAlign: 'center',
            background: '#364d79',
        },
        inputValue: 1000,
        open: false,
        imageUrl: '',
        loading: false,
        fileList: [],
        navlist: []
    }
    getProList = async () => {
        let res = await Pro['getprolist']()
        this.setState({
            proList: res.data.reverse(),
            page: 1
        })
        console.log(res.data);

    }
    getNavlist = async () => {
        let res = await Pro["getNavlist"]()
        console.log(res.data,"nav");
        this.setState({
            navlist: res.data
        })
    }
    componentDidMount() {
        this.getProList()
        this.getNavlist()
    }
    change = (val) => {
        this.setState({
            proList: this.state.proList.filter(item => item.proname.includes(val))
        })
    }
    update = async (id, isShow) => {
        let res = await Pro['changeisshow']({ id, isShow })
        console.log(res.data);
        if (res.code === 200) {
            this.getProList()
            message.success({
                content: res.data.message
            })
        }
    }

    show = () => {
        this.setState({
            open: true
        })
    }
    close = () => {
        this.setState({
            open: false
        })
    }
    onFinish = async (value) => {
        console.log(value.time);
        const time = [[(value.time[0].format().split("T")[0].split("-")[1] + '月'), (value.time[0].format().split("T")[0].split("-")[2] + '日')].join(''), [(value.time[0].format().split("T")[0].split("-")[1] + '月'), (value.time[1].format().split("T")[0].split("-")[2] + '日')].join('')].join("至");
        const day1 = new Date([value.time[1].format().split("T")[0], value.time[1].format().split("T")[1].split('+')[0]].join(' ')).getTime();
        const day2 = new Date([value.time[0].format().split("T")[0], value.time[1].format().split("T")[1].split('+')[0]].join(' ')).getTime();
        const days = (day1 - day2) / (1000 * 3600 * 24)
        const banners = value.banners.fileList.map(item => item.response.data[0])
        const zanshidata = { ...value, banners, time, isHeart: false, isShow: true, id: Date.now(), score: 0, distance: "0", days: days }
        console.log(zanshidata, "data");
        let res = await Pro["addprolist"](zanshidata)
        console.log(res.code);
        if (res.code === 200) {
            message.success({
                content: res.data.message
            })
            this.getProList()
        }
    }
    onChangeS = (newValue) => {
        this.setState({
            inputValue: newValue
        })
    };
    todel =async(id)=>{
        console.log(id);
        let res = await Pro["delprolist"](id)
        console.log(res);
        message.success({
            content: res.data.message
        })
        this.getProList()
    }
    handleChange = (info) => {
        if (info.file.status === 'uploading') {
            this.setState({
                loading: true
            })
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            if (info.file.response.code == 200) {
                this.setState({
                    imageUrl: info.file.response.data[0],
                    photoList: this.state.photoList.push(info.file.response.data[0])
                })
                console.log(this.state.photoList);

            }
        }
    };
    render() {

        const { page, proList, navlist, open, inputValue, fileList, contentStyle } = this.state
        const { RangePicker } = DatePicker
        const columns = [{
            width: "60px",
            title: "序号",
            render: (_, row, index) => <span>{(page - 1) * 10 + index + 1}</span>
        },
        {
            width: "160px",
            title: "房源轮播图",
            render: (_, row, index) => <Carousel afterChange={this.onChange} autoplay>
                {row.banners.map((item) => <div>
                    <img src={item} style={contentStyle} width={150}></img>
                </div>)}
            </Carousel>
        }, {
            width: "200px",
            title: "房源名称及省份",
            render: (_, row, index) => <span>{row.proname}</span>
        }, {
            width: 90,
            title: "房源距离",
            render: (_, row, index) => <span>{row.distance}公里</span>
        }, {
            title: "房源时间及单价",
            width: 240,
            ellipsis: true,
            render: (_, row, index) => <div> <span >{row.time}</span> <span style={{ paddingLeft: 10 }}>￥{row.price}</span></div>
        },
        {
            width: 100,
            title: "房源类别",
            ellipsis: true,
            render: (_, row, index) => <div>{this.state.navlist.filter(item => item.id === row.categoryId)[0]?.title}</div>
        }, {
            width: 95,
            title: "房源评分",
            render: (_, row, index) => <Progress type="circle" percent={row.score * 20} strokeColor={{ '0%': '#108ee9', '100%': '#87d068' }} size="small" format={(num) => num / 20 + "分"} />
        }
            , {
            width: 80,
            title: "是否展示",
            render: (_, row, index) => <Switch onChange={() => this.update(row.id, row.isShow)} checked={row.isShow}></Switch>
        }
        , {
            width: 80,
            title: "操作",
            render: (_, row, index) => <Button size='small' onClick={()=>{this.todel(row.id)}}>删除</Button>
        }
        ]
        return (

            <div>
                <div style={{ margin: "10px 0" }}>
                    <Button onClick={this.show} style={{ marginLeft: 20 }}>添加新房源</Button>
                </div>
                <Input.Search placeholder='请输入' style={{ padding: 15 }} onChange={(e) => {
                    if (e.target.value === '') {
                        this.getProList()
                    }
                }} onSearch={this.change} />
                <Table rowKey='id' dataSource={proList} columns={columns} />
                <Drawer open={open} onClose={this.close} title={'添加新房源'} width={850} style={{ zIndex: "10" }}>
                    <Form
                        name="basic"
                        labelCol={{
                            span: 8,
                        }}
                        wrapperCol={{
                            span: 16,
                        }}
                        style={{
                            maxWidth: 600,
                        }}
                        initialValues={{
                            remember: true,
                        }}
                        onFinish={this.onFinish}
                        onFinishFailed={this.onFinishFailed}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="房源名称以及所在省份"
                            name="proname"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入房源名称以及所在省份',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="房源单价"
                            name="price"
                        >
                            <Slider min={1000} max={8000} onChange={this.onChangeS} value={typeof inputValue === 'number' ? inputValue : 0} step={0.01} />
                        </Form.Item>

                        <Form.Item label="房源可租日期" name="time" >
                            <RangePicker format={'YYYY/MM/DD'} />
                        </Form.Item>
                        <Form.Item label="房源类别" name="categoryId" >
                            <Select
                                style={{ width: 120 }}
                                options={navlist.map((item) => { return { value: item.id, label: item.title } })}
                            />
                        </Form.Item>
                        <Form.Item
                            label="房源图片"
                            name="banners"
                        >
                            <Upload
                                action="http://114.116.29.103:8089/upload"
                                listType="picture"
                                defaultFileList={[...fileList]}
                            >
                                <Button icon={<UploadOutlined />}>Upload</Button>
                            </Upload>
                        </Form.Item>

                        <Form.Item
                            wrapperCol={{
                                offset: 8,
                                span: 16,
                            }}
                        >
                            <Button type="primary" htmlType="submit" >
                                添加房源
                            </Button>
                        </Form.Item>
                    </Form>
                </Drawer>
            </div>
        )
    }
}

export default Index;
